// src/shared/utils/storage.ts

// 定义存储键常量
export const STORAGE_KEYS = {
  USERS: 'mall_users',
  PRODUCTS: 'mall_products',
  HOT_PRODUCTS: 'mall_hot_products',
  CATEGORIES: 'mall_categories',
  ADDRESSES: 'mall_addresses',
  CART_ITEMS: 'mall_cart_items',
  ORDERS: 'mall_orders',
  ORDER_ITEMS: 'mall_order_items',
  BANNERS: 'mall_banners',
  CURRENT_USER: 'mall_current_user'
} as const;

/**
 * 从localStorage获取数据
 * @param key 存储键
 * @returns 解析后的数据数组，如果不存在则返回空数组
 */
export const getStorageData = <T>(key: string): T[] => {
  try {
    const data = localStorage.getItem(key);
    return data ? JSON.parse(data) : [];
  } catch (error) {
    console.error(`Error reading from localStorage with key: ${key}`, error);
    return [];
  }
};

/**
 * 向localStorage保存数据
 * @param key 存储键
 * @param data 要保存的数据
 */
export const setStorageData = <T>(key: string, data: T[]): void => {
  try {
    localStorage.setItem(key, JSON.stringify(data));
  } catch (error) {
    console.error(`Error writing to localStorage with key: ${key}`, error);
  }
};

/**
 * 从localStorage获取单个对象数据
 * @param key 存储键
 * @returns 解析后的数据对象，如果不存在则返回null
 */
export const getStorageItem = <T>(key: string): T | null => {
  try {
    const data = localStorage.getItem(key);
    return data ? JSON.parse(data) : null;
  } catch (error) {
    console.error(`Error reading item from localStorage with key: ${key}`, error);
    return null;
  }
};

/**
 * 向localStorage保存单个对象数据
 * @param key 存储键
 * @param data 要保存的数据对象
 */
export const setStorageItem = <T>(key: string, data: T): void => {
  try {
    localStorage.setItem(key, JSON.stringify(data));
  } catch (error) {
    console.error(`Error writing item to localStorage with key: ${key}`, error);
  }
};

/**
 * 删除localStorage中的数据
 * @param key 存储键
 */
export const removeStorageData = (key: string): void => {
  try {
    localStorage.removeItem(key);
  } catch (error) {
    console.error(`Error removing from localStorage with key: ${key}`, error);
  }
};

/**
 * 清空所有商城相关的localStorage数据
 */
export const clearAllMallData = (): void => {
  Object.values(STORAGE_KEYS).forEach(key => {
    removeStorageData(key);
  });
};

/**
 * 检查localStorage中是否存在指定键的数据
 * @param key 存储键
 * @returns 是否存在数据
 */
export const hasStorageData = (key: string): boolean => {
  const data = localStorage.getItem(key);
  return data !== null && data !== undefined;
};

/**
 * 获取localStorage中数组数据的长度
 * @param key 存储键
 * @returns 数组长度
 */
export const getStorageDataLength = (key: string): number => {
  return getStorageData(key).length;
};